package demo.api.ding;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author junying.han
 */
public class DingUtils {

    /**
     * 钉钉消息长度限制
     */
    public static final int MSG_LIMIT = 4096;
    public static final String OAPI_HOST = "https://oapi.dingtalk.com";
    public static final String CORP_ID = "ding51f195092fd77474";
    public static final String CORP_SECRET = "S5oe8UKsrPRygOfyJhzI74PqGZU4JxFAEX-Kmqk1F6Dg3P-X2h4HMNdL5iSxvElY";
    // 发送群消息的用户id,必须有一个
    public static final String SENDER = "3141";
    private static final String MSG_TYPE = "msgtype";
    private static Logger logger = LoggerFactory.getLogger(DingUtils.class);
    private static LoadingCache<String, String> access_token_Cache = CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.MINUTES).maximumSize(300).build(new CacheLoader<String, String>() {
                @Override
                public String load(String access_token) {
                    try {
                        return getAccessToken();
                    } catch (Throwable e) {
                        logger.error("getAccessToken failed", e);
                        return "a85a01573e8d302a8bc0ac807e9ceee6";
                    }
                }
            });

    /**
     * 获取访问的token
     *
     * @return
     */
    private static String getAccessToken() {
        JSONObject reponseJson = DingTalkApiUtils.getToken();
        logger.warn("getToken return:{}", reponseJson);
        return reponseJson.getString("access_token");
    }


    /**
     * @param url
     * @param pcSlide true：表示在PC客户端侧边栏打开; false：表示在浏览器打开
     * @return
     * @see <a href="https://open.dingtalk.com/document/orgapp-server/message-link-description">参考</a>
     */
    public static String buildActionCardUrl(String url, boolean pcSlide) {
        try {
            String encodeUrl = URLEncoder.encode(url, StandardCharsets.UTF_8.displayName());
            return String.format("dingtalk://dingtalkclient/page/link?url=%s&pc_slide=%s", encodeUrl, pcSlide);
        } catch (Exception e) {
            logger.error("buildActionCardUrl failed, url: {}", url, e);
            return url;
        }
    }


}
